import config
import json
from flask import Flask, render_template, request, Response, session
from flask_sqlalchemy import SQLAlchemy

from configPhoneMessage import sendMessageFunction, sendDangerMessage
from src.opencv.camera import Camera

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy()
db.init_app(app=app)

from src.domain.roomStatus import RoomStatus

from src.impl.roomImpl import room_status_update, get_video_type, get_roomstatus_by_roomid
from src.impl.userImpl import *

from src.domain.log import Log
from src.impl.logImpl import add_log, get_log_by_roomid, delete_log_by_path, get_log_by_search


# 进入首页
@app.route('/')
def index():
    print(0)
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():  # put application's code here
    username = request.args.get('username')
    password = request.args.get('password')
    global user
    user = get_user_by_username_and_password(username, password).first()
    # 用户存在
    if user:
        roomid = user.roomid
        try:
            rlist = get_roomstatus_by_roomid(roomid)
            # print(rlist)
            global roomstatus
            roomstatus = rlist[0]
            print(user)
            return render_template('main.html', user=user, roomstatus=roomstatus)

        except Exception as e:
            print(e)
    else:
        msg = "密码错误"
        return render_template('index.html', msg=msg)


# 进行注册
@app.route('/register', methods=['GET', 'POST'])
def getLRegisterRequest():
    msg = ""
    # 判断两次密码是否相同
    if request.args.get('passwordR') != request.args.get('repeatPassword'):
        return render_template('index.html', msg="两次输入的密码不同，请检查")

    # 判断用户名是否重复
    username = request.args.get("usernameR")
    password = request.args.get("passwordR")
    roomid = request.args.get("RoomIDR")
    user1 = get_user_by_username(username)
    if user1:
        return render_template('index.html', msg="用户名重复")
    else:
        # 插入
        add_user(username, password, roomid)
        return render_template('index.html', msg="注册成功")


# 忘记密码跳往修改密码界面
@app.route('/forgetPassword', methods=['GET', 'POST'])
def forgetPassword():
    return render_template('forgetPassword.html')


# 发送短信验证码
@app.route('/sendMessage', methods=['GET', 'POST'])
def sendMessage():
    # 发送短信
    phoneNumber = request.args.get('phoneNumber')
    print(phoneNumber)
    if (phoneNumber != None):
        code = sendMessageFunction(phoneNumber)
    else:
        return "fail"
    if (code == 0):
        print("success")
        return "success"
    else:
        print("fail")
        return "fail"


# 修改密码
@app.route('/editPassword', methods=['GET', 'POST'])
def editPassword():
    password = request.args.get("password")
    number = request.args.get("number")
    verifyCode = request.args.get("verifyCode")
    code = session.get("code")
    # 判断验证码是否正确
    if (verifyCode == code):
        user1 = get_user_by_phoneNumber(number)
        message = update_user(user1.username, password, number, user1.roomid)
        return message
    else:
        return "验证码错误"


@app.route('/main')
def viewMain():
    # global room_status
    # rList = get_roomstatus_by_roomid(114)
    # room_status=rList[0]
    print(roomstatus.temperature)
    return render_template('main.html', roomstatus=roomstatus, user=user)


@app.route('/roomstatus')
def view_room_status():
    uList = get_user_by_roomId(user.roomid)

    return render_template('roomStatus.html', uList=uList, roomstatus=roomstatus)


@app.route("/updateStatus", methods=['POST'])
def update_room_status():
    print('---')
    print(str(request.get_data(), encoding='utf-8'))
    get_data = json.loads(str(request.get_data(), encoding='utf-8'))
    print(get_data)

    roomstatus.roomid = get_data["roomId"]
    roomstatus.temperature = get_data["temperature"]
    roomstatus.moisture = get_data["moisture"]
    roomstatus.door = get_data["door"]
    roomstatus.electricity = get_data["electricity"]
    msg = get_video_type(roomstatus)
    sendDangerMessage(user.telephone, msg)
    return room_status_update(roomstatus)


@app.route('/video')
def video():
    """视频流主页"""

    return render_template('video.html')


def gen():
    """视频流生成函数"""
    global camera
    camera = Camera()
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    """视频流路由(route).放到 img 标签的 src 属性."""
    return Response(gen(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


@app.route('/test')
def test():
    log = Log()
    log.roomId = roomstatus.roomid
    log.time = camera.time
    log.reason = get_video_type(roomstatus)
    log.video = camera.fileName
    add_log(log)
    camera.out.release()
    return render_template('main.html', roomstatus=roomstatus, user=user)


@app.route('/records')
def view_record():
    roomid = user.roomid
    lList = get_log_by_roomid(roomid)
    print(lList)
    return render_template("record.html", records=lList)


@app.route('/search')
def search():
    keyword = request.args.get("keyword")
    roomid = user.roomid
    print(keyword)
    print(roomid)
    lList = get_log_by_search(roomid, keyword)
    print(lList)
    return render_template("record.html", records=lList)


@app.route('/viewrecord', methods=['GET'])
def viewrecord():
    recordSrc = './video/' + request.args.get('recordSrc', None)
    print(recordSrc)
    videopath = recordSrc
    return render_template("viewrecord.html", videopath=videopath)


@app.route('/deleterecord', methods=['GET'])
def deleterecord():
    recordSrc = request.args.get('recordSrc', None)
    print(recordSrc)
    delete_log_by_path(recordSrc)
    roomid = user.roomid
    lList = get_log_by_roomid(roomid)
    return render_template("record.html", records=lList)


@app.route("/messageLoginIndex")
def messageLoginIndex():
    return render_template("messageLogin.html")


@app.route("/messageLogin", methods=['GET', 'POST'])
def messageLogin():
    number = request.args.get("phoneNumber")
    print(number)
    verifyCode = request.args.get("validationCode")
    global user
    user = get_user_by_phoneNumber(phoneNumber=number)
    code = session.get("code")
    print(code)
    if user:
        if code == verifyCode:
            roomid = user.roomid
            rlist = get_roomstatus_by_roomid(roomid)
            print(rlist)
            global roomstatus
            roomstatus = rlist[0]
            return render_template('main.html', roomstatus=roomstatus, user=user)
        else:
            return render_template('index.html', msg="验证码错误")
    else:
        print("失败")
        return render_template('index.html', msg="用户名不存在")


@app.route('/viewtimetable')
def viewtimetable():
    return render_template('timetable.html')


@app.route('/vieweditaccount')
def vieweditaccount():
    return render_template("editaccount.html", user=user)


@app.route('/editaccount', methods=['GET', 'POST'])
def editaccount():
    password = request.args.get("password")
    passwordr = request.args.get("passwordr")
    telephone = request.args.get("telephone")
    roomid = request.args.get("roomid")

    if (passwordr == password):
        user.password = password
        user.telephone = telephone
        user.roomid = roomid
        msg = "修改成功"
        update_user(user.username, password, telephone, roomid)
        return render_template("editaccount.html", msg=msg, user=user)
    else:
        msg = "两次密码输入不一致"
        return render_template("editaccount.html", msg=msg, user=user)


@app.route('/viewroomates')
def viewroomates():
    return render_template("roomates.html")


if __name__ == '__main__':
    app.run()
